package com.lzh.async.thread;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.concurrent.Callable;

/**
 * @author zhehen.lu
 * @date 2025/8/13 19:49
 */
public class RequestContextAwareCallable<T> implements Callable<T> {
    private Callable<T> task;
    private RequestAttributes context;

    public RequestContextAwareCallable(Callable<T> task, RequestAttributes context) {
        this.task = task;
        this.context = context;
    }

    @Override
    public T call() throws Exception {
        if (this.context != null) {
            RequestContextHolder.setRequestAttributes(this.context);
        }

        Object object;
        try {
            object = this.task.call();
        } finally {
            RequestContextHolder.resetRequestAttributes();
        }

        return (T) object;
    }
}
